package okhttp3.guide;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.net.ssl.HttpsURLConnection;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Dns;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class GetExample2 {
	  private static final Logger logger = Logger.getLogger(GetExample2.class.getName());
	 static OkHttpClient client1;
	
	 
  String run(String url) throws IOException {
	  
	  Request request = new Request.Builder()	
        .url(url)
        .build();
	 
	 client1.newCall(request).enqueue(new Callback() {
			
			@Override
			public void onResponse(Call call, Response response) throws IOException {
				 System.out.println("2 call thread name "+Thread.currentThread().getName()+"  call  "+response.body().string());
			}
			
			@Override
			public void onFailure(Call call, IOException e) {
				e.printStackTrace();
			}
		});
//    try (Response response = client.newCall(request).execute()) {
//      return response.body().string();
//    }
    return "1";
  }
  /**
   * 1.http和https之间不可互相转换，比如 http://www.cssmoban.com/ 在dns中配置 返回www.baidu.com的InetAddress，会出现响应不出来
   * https://www.baidu.com/ 在dns转换成http的类型的，会抛出异常毕竟走加密
   * 2.ip应该是可以和http可以互相转换
   * 应用场景：环境切换，httpDNS 可以总结
   *  	踩坑：环境切换必须必须是 host后面资源位置描述还是一样的才可以
   */
  public static void main(String[] args) throws IOException {
	  OkHttpClient.Builder builder = new OkHttpClient.Builder();
	  builder.dns(new Dns() {
		
		@Override
		public List<InetAddress> lookup(String hostname) throws UnknownHostException {
			Map<String,List<InetAddress>> map = new HashMap<>();
			InetAddress address = InetAddress.getByName("67zixue.com");
			List<InetAddress> list = new ArrayList<>();
			list.add(address);
			//ip地址还是调用java方法，只不过会直接返回
			map.put("192.168.5.223", list);
			if(map.containsKey(hostname)) {
				return map.get(hostname);
			}
			List<InetAddress>  adds = Dns.SYSTEM.lookup(hostname);
			System.out.println(adds.toString());
			return adds;
		}
	});
	  
	  client1 = builder.build();
    GetExample2 example = new GetExample2();
   // String response = example.run("https://raw.github.com/square/okhttp/master/README.md");//https://www.baidu.com/
   //String response = example.run("http://67zixue.com/home/article/detail/id/32.html");
    String response = example.run("http://192.168.5.223:7300/mock/5cad5c0ead170a13bc0f138c/driverDemo/driverpad/api/notification/unread/count");
     
    System.out.println(response);
  }
  

}
